'use strict';
let uniID = require('uni-id')
const createConfig = require('uni-config-center')
const uniIdConfig = createConfig({
	pluginId: 'uni-id'
}).config()
const db = uniCloud.database()

exports.main = async (event, context) => {
	let { action,params,uniIdToken } = event
	let payload  = ''
	//UNI_WYQ:这里的uniID换成新的，保证多人访问不会冲突
	const uniIDIns = uniID.createInstance({ // 创建uni-id实例，其上方法同uniID
	    context: context,
	    // config: {} // 完整uni-id配置信息，使用config.json进行配置时无需传此参数
	  })
	
	let noCheckAction = [//这些接口不需要token检测
		'checkToken', 
		'login'
	]
	if (!noCheckAction.includes(action)) {
		if (!uniIdToken) {
			return {
				code: 403,
				msg: '缺少token或token已过期，请重新登录！'
			}
		}
		payload = await uniIDIns.checkToken(uniIdToken)// 后续使用uniIDIns调用相关接口进行token检测
		if (payload.code && payload.code > 0) {
			await uniID.logout(uniIdToken)
			return payload
		}
	}
	
	
	switch (action){
		case "login":
			let {username,password} = params
			let res = await uniIDIns.login({
				username,
				password
			})
			//返回数据给客户端
			return res;
			break;
		case "logout":
			let logout_data = await uniID.logout(uniIdToken)
			return logout_data
			break;
		case "get_avatar":
			let get_avatar_data = await uniID.getUserInfo({
			    uid: payload.uid,
			    field: ['avatar']
			})
			return get_avatar_data
			break;
		case "updata_avatar":
			let { avatar_url } = params
			let updata_avatar_data = await uniID.setAvatar({
					uid: payload.uid,
			        avatar:avatar_url
			    })
			return updata_avatar_data
			break;
		case "autoLogin":
			let toPage = "../index/index"
			let {user_id} = params
			let userInfo = '';
			await db.collection('uni-id-users').where({
				_id:user_id
			}).get().then((res)=>{
				userInfo = res
			})
			//返回数据给客户端
			return {toPage,userInfo};
			break;
		case "getUserRole":
			let {userRole} = params
			let resall = '';
			await db.collection('uni-id-roles').where({
				role_id:userRole
			}).get().then((res)=>{
				resall = res
			})
			return resall
			break;
		case "lookhouse":
			let {
				cart_name_lookhouse,
				cart_depository_lookhouse,
				cart_type_lookhouse,
				num,
				isall
			} = params
			let res_lookhouse = {}
			if(isall){
				let Olength = 0;
				await db.collection('yt-depository-carts').get().then((res)=>{
					Olength = res.data.length
				})
				await db.collection('yt-depository-carts').limit(num).get().then((res)=>{
					res_lookhouse = {
						code:0,
						msg:'查询成功！',
						Olength,
						data:res
					}
					
				}).catch(()=>{
					res_lookhouse = {
						code:1,
						msg:'库存查询失败！'
					}
				})
			}else if(cart_name_lookhouse == ""){
				let Olength = 0;
				await db.collection('yt-depository-carts').where({
					cart_depository:cart_depository_lookhouse,
					cart_type:cart_type_lookhouse
				}).get().then((res)=>{
					Olength = res.data.length
				})
				await db.collection('yt-depository-carts').where({
					cart_depository:cart_depository_lookhouse,
					cart_type:cart_type_lookhouse
				}).limit(num).get().then((res)=>{
					res_lookhouse = {
						code:0,
						msg:'查询成功！',
						Olength,
						data:res
					}
				}).catch(()=>{
					res_lookhouse = {
						code:1,
						msg:'库存查询失败！'
					}
				})
			}else{
				let Olength = 0;
				await db.collection('yt-depository-carts').where({
					cart_name:cart_name_lookhouse,
					cart_depository:cart_depository_lookhouse,
					cart_type:cart_type_lookhouse
				}).get().then((res)=>{
					Olength = res.data.length
				})
				await db.collection('yt-depository-carts').where({
					cart_name:cart_name_lookhouse,
					cart_depository:cart_depository_lookhouse,
					cart_type:cart_type_lookhouse
				}).limit(num).get().then((res)=>{
					res_lookhouse = {
						code:0,
						msg:'查询成功！',
						Olength,
						data:res
					}
				}).catch(()=>{
					res_lookhouse = {
						code:1,
						msg:'库存查询失败！'
					}
				})
			}
			return res_lookhouse
			break;
		case "enterhouse":
			let {
				cart_name_enterhouse,
				cart_id_enterhouse,
				cart_type_enterhouse,
				cart_depository_enterhouse,
				cook_utensils_jf_enterhouse,
				cook_utensils_cf_enterhouse,
				cook_utensils_eyes_enterhouse,
				cook_utensils_qtype_enterhouse,
				cart_num_enterhouse,
				comment_enterhouse
			} = params
			let res_enterhouse = {}
			for(var i = 0;i < cart_num_enterhouse;i ++){
				await db.collection('yt-depository-carts').add({
					cart_name:cart_name_enterhouse,
					cart_id:cart_id_enterhouse,
					cart_type:cart_type_enterhouse,
					cart_depository:cart_depository_enterhouse,
					cook_utensils_jf:cook_utensils_jf_enterhouse,
					cook_utensils_cf:cook_utensils_cf_enterhouse,
					cook_utensils_eyes:cook_utensils_eyes_enterhouse,
					cook_utensils_qtype:cook_utensils_qtype_enterhouse,
					cart_num:1,
					comment:comment_enterhouse
				}).then(()=>{
					res_enterhouse = {
						code:0,
						msg:'入库成功！'
					}
				}).catch(()=>{
					res_enterhouse = {
						code:1,
						msg:'入库失败！'
					}
				})
			}
			return res_enterhouse
			break;
		case "outerhouse_sp":
			let {
				applicant_id_outerhouse,
				applicant_outerhouse,
				outhouse_outerhouse,
				transferhouse_outerhouse,
				client_outerhouse,
				client_phone_outerhouse,
				client_local_outerhouse,
				number_outerhouse,
				cart_names_outerhouse,
				istransfer_outerhouse,
				comment_outerhouse
			} = params
			let res_outerhouse_sp = {}
			await db.collection('yt-spOuthouse').add({
				applicant_id:applicant_id_outerhouse,
				applicant:applicant_outerhouse,
				applicant_sp:'',
				applicant_sp_id:'',
				outhouse:outhouse_outerhouse,
				transferhouse:transferhouse_outerhouse,
				client:client_outerhouse,
				client_phone:client_phone_outerhouse,
				client_local:client_local_outerhouse,
				number:number_outerhouse,
				cart_names:cart_names_outerhouse,
				istransfer:istransfer_outerhouse,
				isagree:"",
				isfinish:false,
				comment:comment_outerhouse,
				create_date:new Date().getTime()
			}).then(()=>{
				res_outerhouse_sp = {
					code:0,
					msg:'提交审批成功！'
				}
			}).catch((err)=>{
				res_outerhouse_sp = {
					code:1,
					msg:'提交审批失败！'
				}
			})
			return res_outerhouse_sp
			break;
		case "outerhouse":
			let {
				cart_id_outerhouse,
				isagree_outerhouse,
				isfinish_outerhouse,
				sp_id_outerhouse,
				applicant_sp_outerhouse,
				applicant_sp_id_outerhouse
			} = params
			let outerhouse = {}
			let haveError = false
			await db.collection('yt-spOuthouse').where({
				_id:sp_id_outerhouse,
				applicant_id:applicant_sp_id_outerhouse
			}).get().then((res)=>{
				let {affectedDocs,data} = res
				if(affectedDocs > 0){
					haveError = true
				}
			}).catch(err=>{
				outerhouse = {
					code:1,
					msg:'校验失败！'
				}
			})
			if(!haveError && isagree_outerhouse){
				let istransfer = '';
				let transferhouse = '';
				let outhouse = '';
				if(typeof cart_id_outerhouse == 'object'){
					await db.collection('yt-spOuthouse').where({
						_id:sp_id_outerhouse
					}).get().then((res)=>{
						let {affectedDocs,data} = res
						istransfer = data[0].istransfer
						transferhouse = data[0].transferhouse
						outhouse = data[0].outhouse
					}).catch(err=>{
						outerhouse = {
							code:1,
							msg:'校验失败！'
						}
					})
					if(istransfer){
						let isremoved = true
						let havemove = []
						for(var s = 0;s<cart_id_outerhouse.length;s++){
							await db.collection('yt-depository-carts').where({
								_id:cart_id_outerhouse[s].cart_id
							}).update({
								cart_depository:transferhouse
							}).then((res)=>{
								let {affectedDocs,update} = res
								havemove.push(affectedDocs)
								console.log(havemove)
							}).catch((err)=>{
								outerhouse = {
									code:1,
									msg:'转库失败！数据库错误！'
								}
							})	
						}
						for(let t = 0;t<havemove.length;t++){
							if(havemove[t] == 0){
								isremoved=false
							}
						}
						if(isremoved){
							await db.collection('yt-spOuthouse').where({
								_id:sp_id_outerhouse,
							}).update({
								isagree:isagree_outerhouse,
								isfinish:isfinish_outerhouse,
								applicant_sp:applicant_sp_outerhouse,
								applicant_sp_id:applicant_sp_id_outerhouse
							}).then(()=>{
								outerhouse = {
									code:0,
									msg:'全部货品转库成功！'
								}
							}).catch(err=>{
								outerhouse = {
									code:1,
									msg:'发生未知错误！'
								}
							})
						}else{
							await db.collection('yt-spOuthouse').where({
								_id:sp_id_outerhouse,
							}).update({
								isagree:isagree_outerhouse,
								isfinish:isfinish_outerhouse,
								applicant_sp:applicant_sp_outerhouse,
								applicant_sp_id:applicant_sp_id_outerhouse
							}).then(()=>{
								outerhouse = {
									code:0,
									msg:'已转库部分货品！'
								}
							}).catch(err=>{
								outerhouse = {
									code:1,
									msg:'发生未知错误！'
								}
							})
						}
					}else{
						let isremoved = true
						let readyremoveArr = []
						for(var s = 0;s<cart_id_outerhouse.length;s++){
							await db.collection('yt-depository-carts').where({
								_id:cart_id_outerhouse[s].cart_id
							}).get().then((res)=>{
								let {affectedDocs,data} = res
								if(data[s].cart_depository != outhouse){
									isremoved = false
								}
							}).catch((err)=>{
								outerhouse = {
									code:1,
									msg:'出库失败！数据库错误！'
								}
							})	
						}
						if(isremoved){
							for(var s = 0;s<cart_id_outerhouse.length;s++){
								await db.collection('yt-depository-carts').where({
									_id:cart_id_outerhouse[s].cart_id
								}).remove().then((res)=>{
									let {affectedDocs,deleted} = res
									readyremoveArr.push(affectedDocs)
									console.log(readyremoveArr)
								}).catch((err)=>{
									outerhouse = {
										code:1,
										msg:'出库失败！数据库错误！'
									}
								})	
							}
							for(let t = 0;t<readyremoveArr.length;t++){
								if(readyremoveArr[t] == 0){
									isremoved=false
								}
							}
							if(isremoved){
								await db.collection('yt-spOuthouse').where({
									_id:sp_id_outerhouse,
								}).update({
									isagree:isagree_outerhouse,
									isfinish:isfinish_outerhouse,
									applicant_sp:applicant_sp_outerhouse,
									applicant_sp_id:applicant_sp_id_outerhouse
								}).then(()=>{
									outerhouse = {
										code:0,
										msg:'出库成功！'
									}
								}).catch(err=>{
									outerhouse = {
										code:1,
										msg:'发生未知错误！'
									}
								})
							}else{
								outerhouse = {
									code:1,
									msg:'出库失败！部分货品不存在！请拒绝审批后，重新申请出库审批！'
								}
							}
						}else{
							outerhouse = {
								code:1,
								msg:'出库失败！部分货品已转库，请拒绝审批后，重新申请出库审批！'
							}
						}
					}
				}else{
					outerhouse = {
						code:1,
						msg:'出库失败！非法的数据请求！'
					}
				}	
			}else if(!haveError && !isagree_outerhouse){
				await db.collection('yt-spOuthouse').where({
					_id:sp_id_outerhouse,
				}).update({
					isagree:isagree_outerhouse,
					isfinish:isfinish_outerhouse,
					applicant_sp:applicant_sp_outerhouse,
					applicant_sp_id:applicant_sp_id_outerhouse
				}).then(()=>{
					outerhouse = {
						code:0,
						msg:'拒绝出库成功！'
					}
				}).catch(err=>{
					outerhouse = {
						code:1,
						msg:'发生未知错误！'
					}
				})
			}else{
				outerhouse = {
					code:1,
					msg:'不可审批自己！'
				}
			}
			return outerhouse
			break;	
		case "looksp":
			let {
				keyword,
				moonth,
				sp_type,
				num_sp,
				isall_sp
			} = params
			let looksp = {}
			if(isall_sp){
				var splength = 0
				await db.collection('yt-spOuthouse').where({
					istransfer:sp_type
				}).get().then((res)=>{
					splength = res.data.length
				})
				await db.collection('yt-spOuthouse').where({
					istransfer:sp_type
				}).limit(num_sp).get().then(res=>{
					looksp = {
						code:0,
						msg:'查询成功！',
						splength,
						data:res
					}
				}).catch(err=>{
					looksp = {
						code:1,
						msg:'审批查询失败！'
					}
				})
			}else if(keyword == ""){
				var splength = 0
				await db.collection('yt-spOuthouse').where({
					create_time:moonth,
					istransfer:sp_type
				}).get().then((res)=>{
					splength = res.data.length
				})
				await db.collection('yt-spOuthouse').where({
					create_time:moonth,
					istransfer:sp_type
				}).limit(num_sp).get().then((res)=>{
					looksp = {
						code:0,
						msg:'查询成功！',
						splength,
						data:res
					}
				}).catch((err)=>{
					looksp = {
						code:1,
						msg:'审批查询失败！'
					}
				})
			}else{
				var splength = 0
				await db.collection('yt-spOuthouse').where({
					applicant:keyword,
					create_time:moonth,
					istransfer:sp_type
				}).get().then((res)=>{
					splength = res.data.length
				})
				await db.collection('yt-spOuthouse').where({
					applicant:keyword,
					create_time:moonth,
					istransfer:sp_type
				}).limit(num_sp).get().then((res)=>{
					looksp = {
						code:0,
						msg:'查询成功！',
						splength,
						data:res
					}
				}).catch((err)=>{
					looksp = {
						code:1,
						msg:'审批查询失败！'
					}
				})
			}
			return looksp
			break;
		default:
			return {
				code:1,
				msg:'非法的请求！'
			}
			break;
	}
};
